package com.handpay.zztong.hp.ui;

import java.text.DecimalFormat;

import android.content.Context;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;

import com.handpay.framework.ui.HPEditText;

/**
 * 控制金额最大值
 *
 * @author cqli
 */
public class MoneyEdit extends HPEditText implements InputFilter {

    private int maxMoney = 1000000;

    public MoneyEdit(Context context, AttributeSet attrs) {
        super(context, attrs);
        // 控制器
        this.setFilters(new InputFilter[]{this});
        this.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    String str = MoneyEdit.this.getText().toString();
                    if (str.length() > 0) {

                        DecimalFormat df = new DecimalFormat();
                        df.applyPattern("#0.00");
                        if (str.equals(".")) {
                            MoneyEdit.this.setText("0.00");
                            return;
                        }
                        MoneyEdit.this.setText(df.format(Double.parseDouble(str)));

                    }
                }
            }
        });
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        //防止100000.99的时候，删除掉点
        if (dend > dstart && dest.toString().substring(dstart, dend).indexOf(".") != -1) {
            String str = dest.toString().replace(".", "");
            //避免'.'的时候，删除，程序就会异常退出
            if (!TextUtils.isEmpty(str) && Double.parseDouble(str) > maxMoney) {
                return ".";
            }
        }
        if (dest.toString().indexOf(".") != -1 && source.toString().indexOf(".") != -1) {
            return "";
        }
        if (!TextUtils.isDigitsOnly(source.toString().replace(".", ""))) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        sb.append(dest);
        sb.insert(dstart, source);
        String str = sb.toString();
        if (str.equals(".")) {
            return source;
        }
        // 控制金额最大值
        else if (!str.equals("") && Double.parseDouble(str) <= maxMoney) {
            // 控制小数点
            if (str.indexOf(".") != -1
                    && str.substring(str.indexOf(".") + 1).length() > 2) {
                return "";
            }
            return source;
        } else {
            return "";
        }
    }

    /**
     * 设置最大金额
     *
     * @param maxMoney
     */
    public void setMaxMoney(int maxMoney) {
        this.maxMoney = maxMoney;
    }
}
